#include "ele_lock_ctrl.h"
#include "elog.h"

int ele_lock_init(void)
{
    int ret = 0;

    rt_pin_mode(ELE_LOCK_P_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(ELE_LOCK_N_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(ELE_LOCK_DET_PIN_1, PIN_MODE_INPUT);
    rt_pin_mode(ELE_LOCK_DET_PIN_2, PIN_MODE_INPUT);
    rt_pin_write(ELE_LOCK_P_PIN, 1);
    rt_pin_write(ELE_LOCK_N_PIN, 1);
    return ret;
}
INIT_APP_EXPORT(ele_lock_init);

/**
 * @brief 电子锁闭合
 * @return int
 */
int ele_lock_close(void)
{
    int ret = 0;
    uint32_t tick = 0;

    rt_pin_write(ELE_LOCK_P_PIN, 0);
    rt_pin_write(ELE_LOCK_N_PIN, 1);
    tick = xTaskGetTickCount();
    while (pdTRUE)
    {
        if (xTaskGetTickCount() - tick >= ELE_LOCK_TIMEOUT)
        {
            ret = -1;
            log_e("close lock tiimeout.");
            goto __exit;
        }
        else if (0 == rt_pin_read(ELE_LOCK_DET_PIN_1)) /* 获取电机锁状态 */
        {
            log_d("close lock success.");
            break;
        }
        osDelay(20);
    }
__exit:
    rt_pin_write(ELE_LOCK_P_PIN, 1);
    rt_pin_write(ELE_LOCK_N_PIN, 1);
    return ret;
}

/**
 * @brief 电子锁打开
 * @return int
 */
int ele_lock_open(void)
{
    int ret = 0;
    uint32_t tick = 0;
    
    rt_pin_write(ELE_LOCK_P_PIN, 1); /* HIGH */
    rt_pin_write(ELE_LOCK_N_PIN, 0); /* LOW */
    tick = xTaskGetTickCount();
    while (pdTRUE)
    {
        if (xTaskGetTickCount() - tick >= ELE_LOCK_TIMEOUT)
        {
            ret = -1;
            log_e("open lock tiimeout.");
            goto __exit;
        }
        else if (1 == rt_pin_read(ELE_LOCK_DET_PIN_1)) /* 获取电机锁状态 */
        {
            log_d("open lock success.");
            break;
        }
        osDelay(20);
    }
__exit:
    rt_pin_write(ELE_LOCK_P_PIN, 1);
    rt_pin_write(ELE_LOCK_N_PIN, 1);
    return ret;
}
